package com.bss.dao;

import java.util.Date;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.andy.basics.Dao;
import com.bss.model.Activity;
import com.bss.model.ActivityType;

@Repository
public class ActivityDao extends Dao<Activity> {

	private static final String DAILY_DEPOSIT_REFUND_REPORT = "Daily Deposit & Refund Report";

	public Activity findLastActivity(final ActivityType activityType) {
		Query query = this.getEntityManager().createQuery(
				"from " + this.getModelClass().getName() + " where activityDate in ( Select max(activityDate) from "
						+ this.getModelClass().getName() + " where activityType = ? )");

		query.setParameter(1, activityType);
		@SuppressWarnings("unchecked")
		List<Activity> list = query.getResultList();

		if ((list == null) || (list.size() == 0)) {
			return null;
		}
		return list.get(0);
	}

	public Date findLastDepositAndRefundReportActivityDate() {
		Query query = this.getEntityManager().createQuery(
				"Select max(a.activityDate) from com.bss.model.Activity a where a.activityType.name = ? ");
		query.setParameter(1, ActivityDao.DAILY_DEPOSIT_REFUND_REPORT);

		return (Date) query.getSingleResult();
	}

	public Activity findLastActivityBefore(final ActivityType activityType, final Date date) {
		Query query = this.getEntityManager().createQuery(
				"Select a from " + Activity.class.getName()
						+ " a where a.activityType = ? and a.activityDate in ( Select max(activityDate) from "
						+ Activity.class.getName() + " where activityDate  < ?  and activityType = ?)");
		query.setParameter(1, activityType);
		query.setParameter(2, date);
		query.setParameter(3, activityType);
		@SuppressWarnings("unchecked")
		List<Activity> list = query.getResultList();

		if ((list == null) || (list.size() == 0)) {
			return null;
		}
		return list.get(0);
	}

}
